package com.aiyige.page.globalsearch;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Keyword;
import com.aiyige.page.globalsearch.adapter.GlobalSearchPagerAdatper;
import com.aiyige.page.globalsearch.adapter.KeywordAssociateAdapter;
import com.aiyige.page.globalsearch.event.EventJumpGlobalSearchTab;
import com.aiyige.page.globalsearch.model.KeywordAssociateItem;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.TaskQueue.TaskQueue;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.GlobalTabSearchPage)
public class GlobalTabSearchPage extends BaseActivity {
    public static final String SEARCH_WORD = "SEARCH_WORD";
    TaskQueue keywordAssociateTaskQueue;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.searchIcon)
    ImageView searchIcon;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    @BindView(R.id.searchBtn)
    TextView searchBtn;
    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.mainVp)
    ViewPager mainVp;
    @BindView(R.id.keywordAssociateRv)
    RecyclerView keywordAssociateRv;
    @BindView(R.id.keywordAssociateLayout)
    FrameLayout keywordAssociateLayout;
    @Autowired
    String searchWord = "";
    KeywordAssociateAdapter keywordAssociateAdapter;
    TextWatcher searchTextWatcher;
    GlobalSearchPagerAdatper gsPagerAdapter;
    Handler mainHandler;
    boolean showKeywordAssociate = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAutoRegisterEventBus(true);
        setContentView(R.layout.page_global_tab_search);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mainHandler = new Handler(Looper.getMainLooper());
        gsPagerAdapter = new GlobalSearchPagerAdatper(getSupportFragmentManager());
        mainVp.setAdapter(gsPagerAdapter);
        tabLayout.setViewPager(mainVp);
        inputEt.setText(searchWord);
        inputEtClearBtn.setVisibility(TextUtils.isEmpty(searchWord) ? View.INVISIBLE : View.VISIBLE);
        searchTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    inputEtClearBtn.setVisibility(View.INVISIBLE);
                    hideKeywordAssociate();
                    keywordAssociateAdapter.setNewData(null);
                } else {
                    inputEtClearBtn.setVisibility(View.VISIBLE);
                    showKeywordAssociate();
                    doKeywordAssociate(s.toString());
                }
            }
        };
        inputEt.addTextChangedListener(searchTextWatcher);
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(v.getText().toString())) {
                        searchWord = v.getText().toString();
                        hideKeywordAssociate();
                        KeyboardUtil.hideKeyboard(v.getContext(), v);
                        gsPagerAdapter.postSearch(searchWord);
                        return true;
                    }
                }
                return false;
            }
        });
        inputEt.setFilters(new InputFilter[]{new InputNumFilter(30, false)});

        keywordAssociateRv.setLayoutManager(new LinearLayoutManager(this));
        keywordAssociateAdapter = new KeywordAssociateAdapter();
        keywordAssociateAdapter.bindToRecyclerView(keywordAssociateRv);
        keywordAssociateAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                searchWord = keywordAssociateAdapter.getItem(position).getKeyword();
                inputEt.removeTextChangedListener(searchTextWatcher);
                inputEt.setText(searchWord);
                inputEt.addTextChangedListener(searchTextWatcher);
                hideKeywordAssociate();
                gsPagerAdapter.postSearch(searchWord);
            }
        });


        keywordAssociateTaskQueue = new TaskQueue("KeywordAssociateTaskQueue");
        keywordAssociateTaskQueue.setCallback(new TaskQueue.Callback() {
            @Override
            public void handleTask(Object object) {
                if (isFinishing() || !showKeywordAssociate) return;
                try {
                    String word = (String) object;
                    final List<KeywordAssociateItem> resultList = new LinkedList<>();
                    if (!TextUtils.isEmpty(word)) {
                        try {
                            Response<ResponseBody> response = ApiManager.getService().searchKeywordAssociate(word).execute();
                            if (response.code() != ResponseCode.OK) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = RetrofitUtil.getResponseBodyAsString(response);
                            List<Keyword> keywordList = JSON.parseArray(json, Keyword.class);
                            for (Keyword keyword : keywordList) {
                                resultList.add(KeywordAssociateItem.newBuilder()
                                        .keyword(keyword.getKeyword())
                                        .build());
                            }
                        } catch (Exception e) {

                        }
                    }
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isFinishing() || !showKeywordAssociate) return;
                            keywordAssociateAdapter.setNewData(resultList);
                        }
                    });
                } catch (Exception e) {

                }
            }
        });
        keywordAssociateTaskQueue.onCreate();
        gsPagerAdapter.postSearch(searchWord);
    }


    private void doKeywordAssociate(String searchStr) {
        keywordAssociateTaskQueue.submitTask(searchStr);
    }

    @Override
    protected void onDestroy() {
        keywordAssociateTaskQueue.onDestroy();
        super.onDestroy();
    }

    public void showKeywordAssociate() {
        showKeywordAssociate = true;
        keywordAssociateLayout.setVisibility(View.VISIBLE);
    }

    public void hideKeywordAssociate() {
        showKeywordAssociate = false;
        keywordAssociateLayout.setVisibility(View.INVISIBLE);
    }

    @OnClick({R.id.titleBackBtn, R.id.inputEtClearBtn, R.id.searchBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                Intent intent = new Intent();
                intent.putExtra(SEARCH_WORD, TextUtils.isEmpty(searchWord) ? "" : searchWord);
                setResult(RESULT_OK, intent);
                finish();
                overridePendingTransition(R.anim.activity_still,0);
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
            case R.id.searchBtn:
                if (!TextUtils.isEmpty(inputEt.getText().toString())) {
                    searchWord = inputEt.getText().toString();
                    hideKeywordAssociate();
                    KeyboardUtil.hideKeyboard(this, inputEt);
                    gsPagerAdapter.postSearch(searchWord);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventJumpGlobalSearchTab event) {
        mainVp.setCurrentItem(event.getIndex());
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(SEARCH_WORD, TextUtils.isEmpty(searchWord) ? "" : searchWord);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_still,0);
    }
}
